package com.sptus.framework.mqtt;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Mqtt连接回调函数 ，用来接收已经订阅的消息
 *
 * @author Mr.Liu
 * @date 2021/4/1 9:36
 */
@Slf4j
@Service
public class MqttReceiveCallback implements MqttCallback {

    @Autowired
    public static MqttReceiveCallback mqttReceiveCallback;

    @SneakyThrows
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("重连");
        MqttClient client = MyMqttClient.mqttClient;
        MqttConnectOptions option = MyMqttClient.mqttConnectOptions;

        option.setCleanSession(true);
        option.setAutomaticReconnect(true);
        while (!client.isConnected()) {
            log.info("emqx重新连接....................................................");
            client.connect(option);
            if (client != null && client.isConnected() ){
                try {
                    client.subscribe("/#", 0);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }else {
                System.out.println("订阅主题失败！mqttClient == null || mqttClient.isConnected() == false");
            }
            Thread.sleep(1000);
        }
    }

//    @PostConstruct
//    public void init() {
//        log.info("初始化");
//        mqttReceiveCallback = this;
//
//    }

//    public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    @Override
    public void messageArrived(String topic, MqttMessage message){

    }
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}

